<?php

namespace app\agent\controller;

use app\common\model\User as UserModel;
use app\common\controller\AgentBase;
use think\Config;
use app\common\model\AuthGroupAccessAgent;
use app\common\model\BetLog;
use think\Session;
use think\Db;

/**
 * 用户管理
 * Class AdminUser
 * @package app\admin\controller
 */
class User extends AgentBase
{
    protected $user_model;
    protected $auth_group_access_agent;
    protected $bet_log_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->user_model = new UserModel();
        $this->auth_group_access_agent = new AuthGroupAccessAgent();
        $this->bet_log_model = new BetLog();
    }

    /**
     * 用户管理
     * @param string $keyword
     * @param int $page
     * @return mixed
     */
    public function index($keyword = '', $page = 1)
    {

        $map = [];
        $user_id = Session::get('agent_id');
        $map['id'] = ['neq', $user_id];
        if ($keyword) {
            $map['username|mobile|email|id|user_nick'] = ['like', "%{$keyword}%"];
        }
        $invite_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']  . url('index/user/index', ['invite_code' => Session::get('agent_uuid')]);
        $map['inviter_id'] = $user_id;
        $user_list = $this->user_model->where($map)->order('id DESC')->paginate(15, false, ['page' => $page]);
        $user_info = $this->user_model->where(['id' => $user_id])->find();

        return $this->fetch('index', ['user_list' => $user_list, 'keyword' => $keyword, 'user' => $user_info, 'invite_url' => $invite_url]);
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add()
    {
        $this->assign('agent_id', Session::get('agent_id'));
        return $this->fetch();
    }

    /**
     * 保存用户
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate_result = $this->validate($data, 'User');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data['password'] = md5($data['password'] . Config::get('salt'));
                if ($this->user_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑用户
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $user = $this->user_model->find($id);

        return $this->fetch('edit', ['user' => $user]);
    }

    /**
     * 更新用户
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate_result = $this->validate($data, 'User');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $user = $this->user_model->find($id);
                $user->id = $id;
                $user->username = $data['username'];
                $user->mobile = $data['mobile'];
                $user->email = $data['email'];
                $user->status = $data['status'];
                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $user->password = md5($data['password'] . Config::get('salt'));
                }
                if ($user->save() !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除用户
     * @param $id
     */
    public function delete($id)
    {
        if ($this->user_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }

    }

    public function stat($userid = 0, $page = 1)
    {
        $data = $this->request->get();
        $where = [];
        $where['user_id'] = $userid;

        $info = $this->user_model->where(['inviter_id' => Session::get('agent_id'), 'id' => $userid])->find();
        if(empty($info)){
           $this->error('你没有权限查看该用户');
        }
        if (!empty($data['publish_time'])) {
            $time = strtotime($data['publish_time']);
            $year = date('Y', $time);
            $month = date('m', $time);
            $day = date('d', $time);

            $where['year'] = $year;
            $where['month'] = $month;
            $where['day'] = $day;
        }
        $log_list = $this->bet_log_model->where($where)->order('bl_id DESC')->paginate(30, false, ['page' => $page]);

        $count = $this->bet_log_model->where(['bet_result' => 1, 'user_id' => $userid])->sum('bet_res_amount');

        $lose = $this->bet_log_model->where(['bet_result' => 2, 'user_id' => $userid])->sum('bet_amount');

        foreach ($log_list as $item => $value) {
            $user_info = $this->user_model->find($value['user_id']);
            $log_list[$item]['username'] = $user_info['username'];
            $log_list[$item]['usernick'] = $user_info['user_nick'];
            if ($value['bet_type'] != 'two_star') {

                $log_list[$item]['bet_detail'] = $this->bet_unit[$value['bet_info']] . '(' . $this->bet_type[$value['bet_type']] . ')';
            } else {
                $bet_data = explode(',', $value['bet_data']);
                $bet_info = explode(',', $value['bet_info']);
                $str = '【二星定位】 ';
                foreach ($bet_data as $items => $val) {
                    $str .= $this->bet_unit[$val] . '(' . $bet_info[$items] . ')  ';
                }
                $log_list[$item]['bet_detail'] = $str;
            }

            $res = Db::name('game_round')->where(['round_qishu' => $value['round_turn']])->find();
            $log_list[$item]['round_result'] = $res['round_result'];
        }

        return $this->fetch('stat', ['userid' => $userid, 'date' => (isset($data['publish_time']) ? $data['publish_time'] : date('Y-m-d')), 'log_list' => $log_list, 'win_count' => $count, 'lose_count' => $lose]);

        $this->assign('userid', $userid);
        $this->assign('log_list', []);
        return $this->fetch();

    }

    public function addcoin($id)
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();


            $agent_info = $this->user_model->where(['id' => Session::get('agent_id')])->find();
            if (!empty($agent_info)) {
                if ($data['amount'] > $agent_info['coin']) {
                    $this->error('代理金币不足');
                }
            }

            try {
                $this->user_model->startTrans();
//                $this->user_model->startStr
                $user = $this->user_model->find($id);
                $user->id = $id;
                $user->coin = bcadd($user->coin, $data['amount']);
                $this->user_model->where(['id' => Session::get('agent_id')])->update(['coin' => bcsub($agent_info['coin'], $data['amount'])]);
                $rs = $user->save();

                $this->user_model->commit();
                if ($rs !== false) {
                    $this->success('更新成功');

                } else {
                    $this->error('更新失败');
                }
            } catch (Exception $e) {
                $this->user_model->rollback();
                $this->error($e->getMessage());

            }
        }


    }

    public function reducecoin($id)
    {
        if ($this->request->isPost()) {
            $msg = '';
            $data = $this->request->post();

            $user = $this->user_model->find($id);
            $coin = bcsub($user->coin, $data['amount']);
            if ($coin < 0) {
                $coin = 0;
                $msg = '减少数量大于现有数量，coin清零';
            }
            $user->id = $id;
            $user->coin = bcsub($user->coin, $data['amount']);
            if ($user->save() !== false) {
                $this->success($msg ? $msg : '更新成功');
            } else {
                $this->error('更新失败');
            }
        }


    }
}